import Queue
import threading

from .split import find_sentences
from .translator import translate

class TranslationThread(threading.Thread):
    def __init__(self, text, from_lang, to_lang):
        super(TranslationThread, self).__init__()

        self.from_lang = from_lang
        self.to_lang = to_lang
        self.work = find_sentences(text)
        self.results = Queue.Queue()
        
        self.running = True
        self.run_lock = threading.Lock()

    def stop(self):
        with self.run_lock:
            self.running = False

    def run(self):
        for sentence in self.work:
            with self.run_lock:
                if not self.running:
                    return

            try:
                rslt = translate(sentence,
                                 self.from_lang,
                                 self.to_lang)
            except ValueError:
                rslt = '<Unable to translate>'
                
            self.results.put((sentence, rslt))

class ResultError(Exception):
    def __init__(self, *args):
        super(ResultError, self).__init__(*args)

class TranslationService(object):
    def __init__(self):
        self.worker = None

    def translate(self, text, from_lang='UNKNOWN', to_lang='ENGLISH'):
        if self.worker:
            self.worker.stop()
        
        self.worker = TranslationThread(text, from_lang, to_lang)
        self.worker.start()
        
    def has_data(self):
        if not self.worker:
            return False
        
        if self.worker.results.empty():
            return False
        
        return True

    def get_result(self):
        if not self.worker:
            raise ResultError('get_result() called with no work in progress')
        if self.worker.results.empty():
            raise ResultError('get_result() called with no available result')
                
        return self.worker.results.get()
